package com.stox.ui.swing.widget.wrapper;

import java.awt.Insets;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import javax.swing.Action;
import javax.swing.Icon;
import javax.swing.KeyStroke;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.core.OrderComparator;
import org.springframework.core.Ordered;

import com.stox.ui.swing.util.ImageIconLoader;
import com.stox.ui.swing.util.SwingUtil;
import com.stox.util.ApplicationContextUtil;


public abstract class JMenuItem extends javax.swing.JMenuItem implements Ordered, InitializingBean{
	private static final long serialVersionUID = -7777150926726897208L;
	
	private Object payload;
	
	public abstract Class<?> getParentClass();
	
	@Override
	public void afterPropertiesSet() throws Exception {
		Collection<JMenuItem> jmenuItems = ApplicationContextUtil.getApplicationContext().getBeansOfType(JMenuItem.class).values();
		List<JMenuItem> children = new ArrayList<JMenuItem>();
		for(JMenuItem jmenuItem : jmenuItems){
			if(getClass().equals(jmenuItem.getParentClass())){
				children.add(jmenuItem);
			}
		}
		OrderComparator.sort(children);
		for(JMenuItem jmenuItem : children){
			add(jmenuItem);
		}
	}
	
	private void init(){
		SwingUtil.initializeWidget(this);
		setMargin(new Insets(0,0,0,0));
		setBorder(null);
	}
	
	public JMenuItem() {
		super();
		init();
	}

	public JMenuItem(Action a) {
		super(a);
		init();
	}

	public JMenuItem(Icon icon) {
		super(icon);
		init();
	}

	public JMenuItem(String text, Icon icon) {
		super(text, icon);
		init();
	}

	public JMenuItem(String text, int mnemonic) {
		super(text, mnemonic);
		init();
	}

	public JMenuItem(String text) {
		super(text);
		init();
	}

	public JMenuItem(String text, int mnemonic, int accelarator, String iconPath){
		this(text);
		setMnemonic(mnemonic);
		setAccelerator(KeyStroke.getKeyStroke(mnemonic, accelarator, true));
		setIcon(ImageIconLoader.loadImageIcon(iconPath));
	}
	
	public JMenuItem(String name, int mnemonic, String iconPath){
		super(name);
		setMnemonic(mnemonic);
		setIcon(ImageIconLoader.loadImageIcon(iconPath));
	}
	
	public Object getPayload() {
		return payload;
	}

	public void setPayload(Object payload) {
		this.payload = payload;
	}

}
